const path = require('path');
const fs = require('fs');
const pump = require("mz-modules/pump");

const {randomFileName} = require('./fs-extend')

function uploadByFile(fileInfo, uploadPath = '') {
  const {filename, filepath, encoding, mime, fieldname} = fileInfo           //从文件信息对象获取信息
  const fileContent = fs.readFileSync(filepath);  //获取文件内容
  fs.unlinkSync(filepath); //异步删除零时区文件
  //带点文件后缀
  const suffixP = path.extname(filename);
  const fileName = randomFileName(fieldname + suffixP)
  const fullPath = path.join(uploadPath, fileName)
  fs.writeFileSync(fullPath, fileContent) //异步写入本地文件
  return {fullPath, fileName, uploadPath, encoding, mime, fieldname}
}

/** fileInFo
"field": "image",
"filename": "GreenanMaze_ZH-CN7987019078_1920x1080.jpg",
"encoding": "7bit",
"mime": "image/jpeg",
"fieldname": "image",
"transferEncoding": "7bit",
"mimeType": "image/jpeg",
"filepath": "C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\egg-multipart-tmp\\blog_back_v2.0\\2020\\08\\30\\16\\ccbb75cc-f60e-4eb3-849a-26995fb277be.jpg"
 */

async function uploadByStream(readStream, uploadPath = '') {
  const {filename, encoding, mime, fieldname} = readStream
  //带点文件后缀
  const suffixP = path.extname(filename);
  //当然这里这样市不行的，因为你还要判断一下是否存在文件路径
  const fileName = randomFileName(fieldname + suffixP)
  const fullPath = path.join(uploadPath, fileName);
  //生成一个文件写入 文件流
  const writeStream = fs.createWriteStream(fullPath);
  //处理，并删除吸入流
  await pump(readStream, writeStream);
  return {fileName, uploadPath, encoding, mime, fieldname, fullPath}
} 

/**
fieldname: 'image',
filename: 'GreenanMaze_ZH-CN7987019078_1920x1080.jpg',
encoding: '7bit',
transferEncoding: '7bit',
mime: 'image/jpeg',
mimeType: 'image/jpeg',
 */

module.exports = {
  uploadByFile,
  uploadByStream
}